<template>
  <div id="announcement-index">
    <div class="main-container container-fluid container-limited page-holder">
      <div class="page-title-holder">
        <h2 class="page-title">公告</h2>
      </div>
      <AnnouncementsList :announcements.sync="announcements" :is-loading="isLoading"/>
      <pagination :current-page="pagination.currentPage" :page-count="pagination.pageCount"/>
      <SendAnnouncement v-if="currentUser.admin" class="m-t-24" v-on:sentAnnc="sentAnnc"/>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import AnnouncementsList from './AnnouncementsList';
import SendAnnouncement from './SendAnnouncement';

export default {
  name: 'AnnouncementIndex', // 公告
  components: { AnnouncementsList, SendAnnouncement },
  data() {
    return {
      announcements: [], // 公告列表数据
      isLoading: false, // 正在加载公告列表
      pagination: { // 翻页组件
        currentPage: null, // 当前页
        pageCount: null, // 总页数
      },
    };
  },
  computed: {
    ...mapState(['currentUser']),
  },
  methods: {
    // 加载公告列表
    loadAnnouncements() {
      this.isLoading = true;
      this.$api.announcements.index({ page: this.$route.query.page })
        .then(res => this.handleRes(res))
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    handleRes(res) {
      this.announcements = res.data;
      this.pagination.currentPage = res.kaminari.current_page;
      this.pagination.pageCount = res.kaminari.total_pages;
    },
    // 发送了公告
    sentAnnc(annc) { this.announcements.unshift(annc); },
  },
  created() { this.loadAnnouncements(); },
};
</script>

<style></style>
